<?php

define('LIBS_PATH', 'libs'.DIRECTORY_SEPARATOR);
define('MODS_PATH', 'modules'.DIRECTORY_SEPARATOR);
define('EXT', '.php');

define('DEF_C', 'api');
define('DEF_M', 'index');
define('DEF_A', '');
define('DEF_R', 'json');


error_reporting(E_ALL);
ini_set("display_errors", 1);
session_start();

include LIBS_PATH.'functions'.EXT;
include LIBS_PATH.'module'.EXT;
include LIBS_PATH.'database'.EXT;


$class = isset($_REQUEST['c']) ? $_REQUEST['c'] : DEF_C;
$method = isset($_REQUEST['m']) ? $_REQUEST['m'] : DEF_M;
$args = isset($_REQUEST['a']) ? $_REQUEST['a'] : DEF_A;
$response = isset($_REQUEST['r']) ? $_REQUEST['r'] : DEF_R;
$hash = isset($_REQUEST['h']) ? $_REQUEST['h'] : NULL;

if($hash === NULL)
{
	$class = 'api';
	$method = 'login';
	$response = DEF_R;
}

$args = preg_replace('/(([^,])+)(,)?/','"$1"$3',$args);

$data = new Stdclass;


$db = Database::getInstance();
$user = $db->prepare('SELECT COUNT(u.dni) num, u.name FROM users u WHERE u.hash = ?',array($hash));
$_SESSION['name'] = $user[0]['name'];
$_SESSION['hash'] = $hash;

unset($db);

if((int)$user[0]['num'] === 0 AND $hash !== NULL)
{
	error($data,'Bad hash');
}
	if(!isset($data->type) OR $data->type !== 'error')
	{
		if(is_file(MODS_PATH.$class.EXT))
			include MODS_PATH.$class.EXT;
		else
			include MODS_PATH.DEF_C.EXT;
		ob_start();
		
		if(class_exists($class))
		{
			$ex = new $class($data);
			if(method_exists($ex,$method))
			{
				eval('$ex->'.$method.'('.$args.');');
			}
			else
				error($data,'This method don\'t exist!');
		}
		else
			error($data,'This class don\'t exist!');
		$err = ob_get_clean();
		unset($ex);
		if($err)
		{
			error($data,'SQL:'.$err);
		}
	}

switch($response)
{
	case 'json':
	default:
		header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
	    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
	    header("Cache-Control: no-store, no-cache, must-revalidate");
	    header("Cache-Control: post-check=0, pre-check=0", false);
	    header("Pragma: no-cache");
		header('Content-type:application/json');
		echo json_encode($data);
	break;
}

?>